package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {


    @Autowired
    private IRoleService roleService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    // 处理查询所有员工请求
    @RequestMapping("/list")
    //@RequiredPermission(name = "员工列表")
    @RequiresPermissions(value = {"employee:list", "员工列表"}, logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        // 把查询的方法的封装参数的形参改成 EmployeeQueryObject 类型，并贴上 @ModelAttribute("qo") 方面前端页面的书写
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        // 查询所有部门数据
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        //int a = 1/0;
        return "employee/list";  // 找视图 /WEB-INF/views/employee/list.jsp
    }

    // ....


    // 处理删除所有员工请求
    @RequestMapping("/delete")
    //@RequiredPermission(name = "员工删除")
    @RequiresPermissions(value = {"employee:delete", "员工删除"}, logical = Logical.OR)

    @ResponseBody
    public JSONResult delete(Long id) {
        try {
            if (id != null) {
                // 传id值就删除对应的员工
                employeeService.delete(id);
            }
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "操作失败, 请联系管理员");
        }

    }

    // 处理是否禁用员工的请求
    @RequestMapping("/disable")
    //@RequiredPermission(name = "员工禁用")
    @RequiresPermissions(value = {"employee:disable", "员工禁用"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult disable(Long id) {
        try {
            employeeService.updateStatus(id);
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "操作失败, 请联系管理员");
        }
    }

    // 处理去新增的请求 http://localhost/employee/input.do
    @RequestMapping("/input")
    @RequiresPermissions(value = {"employee:input", "员工编辑"}, logical = Logical.OR)
    public String input(Long id, Model model) {

        model.addAttribute("roles", roleService.listAll());

        //  查询所有部门往模型存入，提供数据，让员工新增修改时显示出来以供用户选择
        model.addAttribute("departments", departmentService.listAll());

        // 传id 去修改
        if (id != null) {
            model.addAttribute("employee", employeeService.get(id));
            System.out.println(employeeService.get(id));
            return "employee/input";
        }
        // 无id 去新增
        return "employee/input";  // 找视图 /WEB-INF/views/employee/input.jsp
    }

    // 处理新增或修改请求 http://localhost/employee/saveOrUpdate.do
    @RequestMapping("/saveOrUpdate")
    //@RequiredPermission(name = "员工新增/修改")
    @RequiresPermissions(value = {"employee:saveOrUpdate", "员工新增/修改"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult saveOrUpdate(Employee employee, Long[] ids) {
        try {
            if (employee.getId() != null) {
                employeeService.update(employee, ids);
            } else {
                employeeService.save(employee, ids);
            }
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "操作失败");
        }
    }


    //跳转到修改密码页面
    @RequestMapping("/inputPwd")
    public String inputPwd(Long id, Model model) {
        if (id != null) {
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
            return "employee/resetPwd";
        }
        return "employee/updatePwd";
    }

    // 修改当前管理员的密码
    @RequestMapping("/updatePwd")
    @RequiresPermissions(value = {"employee:updatePwd", "员工修改当前密码"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult updatePwd(Long id, String oldPassword, String newPassword) {
        try {
            if (id != null) {
                employeeService.resetPassword(id, newPassword);
            } else {
                employeeService.updatePassword(oldPassword, newPassword);
            }
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, e.getMessage());
        }
    }

    // 修改当前管理员的密码
    @RequestMapping("/batchDelete")
    @RequiresPermissions(value = {"employee:batchDelete", "员工批量删除"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult batchDelete(Long[] ids) {
        employeeService.batchDelete(ids);
        return new JSONResult();
    }

    // 修改当前管理员的密码
    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(Long id, String name) {
        Employee employee = employeeService.selectByName(name);
        HashMap map = new HashMap();
        System.out.println("id: " + id);
        System.out.println("employeeId: " + employee.getId());
        System.out.println("employee.getId() == id: " + (employee.getId().equals(id)));
        //map.put("valid", id == null ?
        //        employee == null : (employee == null ? true : employee.getId() == id));
        map.put("valid", employee == null ? true : employee.getId().equals(id));
        return map;
    }

    // 修改当前管理员的密码
    @RequestMapping("/exportXls")
    @RequiresPermissions(value = {"employee:exportXls", "员工导出"}, logical = Logical.OR)
    public void exportXls(HttpServletResponse response) throws IOException {

        // 设置文件下载的响应头
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        // 使用poi创建一个excel
        Workbook wb = employeeService.exportXls();

        // 把excel的数据输出到浏览器的响应流中
        wb.write(response.getOutputStream());
    }

    // 修改当前管理员的密码
    @RequestMapping("/importXls")
    @RequiresPermissions(value = {"employee:importXls", "员工导入"}, logical = Logical.OR)
    @ResponseBody
    public JSONResult importXls(MultipartFile file) throws IOException {
        employeeService.importXls(file);
        return new JSONResult();
    }

    // 修改当前管理员的密码
    @RequestMapping("/listByLocalDept")
    @ResponseBody
    public HashMap getCurrentDept(Model model) {
        Long deptId = employeeService.getCurrentDept();
        HashMap map = new HashMap();
        map.put("deptId", deptId);
        return map;
    }
}

